package com.face.server.filter;

import com.alibaba.fastjson.JSON;
import com.face.RespMsg;
import com.face.server.entity.Student;
import com.util.JWTUtils;
import io.jsonwebtoken.Jwts;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * jwt 检测
 */
public class UserFilter implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o)
            throws Exception {
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "jwt");
        httpServletResponse.setHeader("Access-Control-Expose-Headers", "jwt");
        httpServletResponse.setCharacterEncoding("UTF-8");

        String jwt = httpServletRequest.getHeader("jwt");
        if (jwt == null) {
            PrintWriter writer = httpServletResponse.getWriter();
            writer.println(JSON.toJSONString(RespMsg.error(-1, "请先登录")));
            return false;
        }
        Student student = JWTUtils.parseJWT(jwt);
        assert student != null;
        httpServletRequest.setAttribute("student", student);
        assert student.getId() != null;
        httpServletRequest.setAttribute("id", student.getId());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
